//
//  CGAboutUs_VC.m
//  Fanmugua
//
//  Created by xiaomk on 2019/11/20.
//  Copyright © 2019 taolang. All rights reserved.
//

#import "CGAboutUs_VC.h"
#import <WebKit/WebKit.h>

@interface CGAboutUs_VC ()<WKNavigationDelegate,UIScrollViewDelegate,UIGestureRecognizerDelegate>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, copy) NSString *content;
@property (nonatomic, strong) UIButton *btnConnect;
@property (nonatomic, strong) CAGradientLayer *gradientLayer;
@end

@implementation CGAboutUs_VC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *typeStr = @"1";
    self.btnConnect.hidden = YES;
    if (self.type ==  CGImagesVCType_UserService) {
        self.navTitle = WXLocalizedString(@"用户协议");
        typeStr = @"1";
    }else if (self.type == CGImagesVCType_helperCenter){
        self.navTitle = WXLocalizedString(@"帮助中心");
        typeStr = @"4";
    }else if (self.type == CGImagesVCType_PayService){
        self.navTitle = WXLocalizedString(@"付款协议");
        typeStr = @"2";
    }else{
        self.navTitle = WXLocalizedString(@"关于我们");
        typeStr = @"3";
    }
    
    [self setNavigationBarTitle:self.navTitle];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(PUB_NAVBAR_HEIGHT);
    }];
    MJWeakSelf
    [APIManager sendGetRequest:[APIURLManager helpConfig] parameters:@{@"helpType":typeStr} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            
            weakSelf.content = requestModel.data[@"helpContent"];
            
            [weakSelf.webView loadHTMLString:weakSelf.content baseURL:nil];
        }else{
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
            
    }];
    
    [self customInitialization];
    
    [self.view addSubview:self.btnConnect];
    [self.btnConnect mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.size.mas_offset(CGSizeMake(130, 42));
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(-27);
    }];
    
}
- (UIButton *)btnConnect{
    
    if (!_btnConnect) {
        
        _btnConnect = [[UIButton alloc] initWithFrame:CGRectMake((kScreenWidth-130)/2, kScreenHeight-42-30, 130, 42)];
        
        [_btnConnect setTitle:@"意见反馈" forState:UIControlStateNormal];
        
        [_btnConnect setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        [_btnConnect setImage:[UIImage imageNamed:@"bfyfk_yjfk"] forState:UIControlStateNormal];
        
        _btnConnect.titleLabel.font = SYSTEM_FONT(14);
        
        [_btnConnect addTarget:self action:@selector(connectAction) forControlEvents:UIControlEventTouchUpInside];
        
        _btnConnect.layer.masksToBounds = YES;
        
        // 设置图片与标题之间的间隔
        CGFloat spacing = 10.0; // 间隔距离

        // 调整 imageView 的位置
        _btnConnect.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing);

        // 调整 titleLabel 的位置
        _btnConnect.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);
        
        _btnConnect.layer.cornerRadius = 42/2;
    }
    return _btnConnect;
}
// 自定义的初始化方法
- (UIImage *)gradientImageWithBounds:(CGRect)bounds colors:(NSArray<UIColor *> *)colors {
    UIGraphicsBeginImageContext(bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // 绘制渐变
    NSMutableArray *cgColors = [NSMutableArray array];
    for (UIColor *color in colors) {
        [cgColors addObject:(__bridge id)color.CGColor];
    }
    
    CGGradientRef gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), (CFArrayRef)cgColors, NULL);
    CGContextDrawLinearGradient(context, gradient, CGPointMake(0, 0), CGPointMake(bounds.size.width, 0), 0);
    
    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return gradientImage;
}

- (void)customInitialization {
    if (_gradientLayer) {
        return;
    }
    
    // 创建渐变背景图
    UIImage *gradientImage = [self gradientImageWithBounds:self.btnConnect.bounds
                                                   colors:@[[UIColor colorWithHexString:@"#6BCF9D"],
                                                            [UIColor colorWithHexString:@"#2EC4AC"]]];
    
    // 设置按钮背景图
    [self.btnConnect setBackgroundImage:gradientImage forState:UIControlStateNormal];
}
- (void)connectAction{
    
}

#pragma mark - WKNavigationDelegate
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation{
//    if (self.chapterInfo.detail.novel.bookCategoryType == CGBookCategoryTypeFilm) {
        [webView evaluateJavaScript:@"var script = document.createElement('script');"
         "script.type = 'text/javascript';"
         "script.text = \"function ResizeImages() { "
         "var myimg,oldwidth;"
         "var maxwidth = 965.0;" // WKWebView中显示的图片宽度
         
         "for(i=0;i <document.images.length;i++){"
         "myimg = document.images[i];"
         "oldwidth = myimg.width;"
         "myimg.width = maxwidth;"
         "}"
         "}\";"
         "document.getElementsByTagName('head')[0].appendChild(script);ResizeImages();" completionHandler:nil];

        //影评 修改字体大小
        [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '240%'" completionHandler:nil];

        //修改字体颜色
//        [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#333333'" completionHandler:nil];
//    }else{
//        //小说 修改字体大小
//        [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '280%'" completionHandler:nil];
//    }
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
//    if (self.chapterInfo.detail.novel.bookCategoryType == CGBookCategoryTypeNovel) {
//        //小说 修改字体大小
//        [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '280%'"
//                  completionHandler:nil];
//    }
}

#pragma mark - ***** lazy ******
- (WKWebView *)webView {
    if (!_webView) {
        _webView = [[WKWebView alloc] init];
        _webView.scrollView.delegate = self;
        _webView.navigationDelegate = self;
        [self.view addSubview:_webView];
    }
    return _webView;
}

@end
